package jsp;

import entity.User;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Random;

/**
 * @author 石小俊
 * @date 2023年10月24日 16:49
 */
@WebServlet("*.code")
public class CodeServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();
        if ("/show.code".equals(path)) {
            showCode(request, response);
        }
        if("/login.code".equals(path)){
            login(request,response);
        }
    }

    protected void showCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Random random = new Random();
        // 在内存中定义一个画板
        BufferedImage image = new BufferedImage(50, 25, BufferedImage.TYPE_INT_RGB);

        // 获取画板中的画笔
        Graphics graphics = image.getGraphics();

        // 设置绘制内容所在的矩形背景
        graphics.fillRect(0, 0, 50, 25);
        // 设置画笔的颜色,随机色
        graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
        // 设置画笔的字体
        graphics.setFont(new Font("宋体", Font.BOLD + Font.ITALIC, 18));

        // 随机生成四位数字或者英文字母
        String s = "0123456789qwertyuiopasdfghjklzxcvbnm";
        StringBuffer buffer = new StringBuffer();
        for(int i =0; i < 4; i++){
            buffer.append(s.charAt(random.nextInt(s.length())));
        }

        // 将验证码内容存放到session,便于校验
        request.getSession().setAttribute("code",buffer.toString());
        System.out.println("验证码:"+buffer);

        // 将随机内容绘制到图片中
        graphics.drawString(buffer.toString(),5,18);
        // 生成图片
        ImageIO.write(image,"JPEG",response.getOutputStream());
    }

    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户输入的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        // 获取图片中的验证码内容
        String image = (String) request.getSession().getAttribute("code");

        // 校验验证码
        if(!code.equals(image)){
            request.setAttribute("loginMsg","验证码不正确");
            request.getRequestDispatcher("/session/login.jsp").forward(request,response);
            return;
        }

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        User user = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where username = ? ")
                    .append(" and password = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs = ps.executeQuery();
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));

                // 当用户名与密码正确,将查询到的数据保存到session中
                // 此时可以通过session中是否存在对应数据判断用户是否已经登录
                request.getSession().setAttribute("user",user);
                response.sendRedirect(request.getContextPath()+"/session/main.jsp");
                return;
            }
            request.setAttribute("loginMsg","用户名或密码错误");
            request.getRequestDispatcher("/session/login.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("loginMsg","服务器内部异常");
            request.getRequestDispatcher("/session/login.jsp").forward(request,response);
        }
    }
}
